public class ThreadDemo2 {
    public static void main(String[] args) {
        //以下i，j为同一个实例对象
        singleInstance i = singleInstance.getInstance();
        singleInstance j = singleInstance.getInstance();
        System.out.println(i.equals(j));
    }
}

class singleInstance {
    private static singleInstance instance = null;
    static Object locker = new Object();
    private singleInstance(){};//使其它类无法通过new方法创建多个实例
    public static singleInstance getInstance() {
        //以下操作非原子性，多线程下可能创建出多个实例
        if (instance == null) {//减少获取释放锁的开销
            while (true) {//不断尝试获取锁
                synchronized (locker) {//通过加锁保证以下操作的原子性
                    if (instance == null) {
                        instance = new singleInstance();
                    }
                    return instance;
                }
            }
        }
        return instance;
    }
}
